package org.boot.fast.filter;

import lombok.extern.slf4j.Slf4j;
import lombok.var;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
@Order(1)
@Component
@WebFilter(urlPatterns = {"/"}, filterName = "corsFilter") //拦截所有请求
public class CorsFilter implements Filter {
    private static final String ALL = "*";
    private static final String MAX_AGE = "3600L";

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        // 设置允许跨域请求应答头
        var response = (HttpServletResponse) resp;
        response.setHeader("Access-Control-Allow-Origin", ALL);
        response.setHeader("Access-Control-Allow-Methods", ALL);
        response.setHeader("Access-Control-Allow-Headers", ALL); // 允许所有请求头
        response.setHeader("Access-Control-Max-Age", MAX_AGE);

        // 处理预检请求
        if ("OPTIONS".equalsIgnoreCase(((HttpServletRequest) request).getMethod())) {
            response.setStatus(HttpServletResponse.SC_OK);
            return; // 结束预检请求
        }
        chain.doFilter(request, response);
    }

}
